import { _decorator, Button, Component, EventHandler, instantiate, Node, Prefab, Widget, SpriteFrame, Label, Sprite, find, Layout } from 'cc';
import { FactoryCom } from '../../Entity/Component/FactoryCom';
import { FactoryBuildItem } from './FactoryBuildItem';
import GameEventMgr, { GameEvent } from '../../Model/GameEventMgr';
import { Tools } from '../../Util/Tools';
import { Workshop } from '../../Entity/Component/SpawnerCom';
import { UICtrl } from '../../Ctrl/UICtrl';
import AssetsMgr from '../../Model/AssetsMgr';
import { Global, RelicData, RelicType, TechnologyData, UnitMsg, UnitType } from '../../Util/Global';
import { TechnologyItem } from './TechnologyItem';
import SoundCtrl from '../../Ctrl/SoundCtrl';
import { RelicItem } from './RelicItem';
const { ccclass, property } = _decorator;

@ccclass('FactoryViewUI')
export class FactoryViewUI extends Component {

    @property({ type: Node })
    public contentRoot: Node = null;
    @property({ type: Node })
    public content: Node = null;
    @property({ type: Label })
    public txtTechnologyPoint: Label = null;

    private itemPrefab_1: Prefab = null;
    private itemPrefab_2: Prefab = null;
    private itemPrefab_3: Prefab = null;

    public target_factory: FactoryCom = null;

    private _isShowTab: boolean = false;

    private currentPageType = 1;
    private unit_icon_prefab: Prefab = null;
    protected start(): void {
        this.contentRoot.active = false;
        this._isShowTab = this.contentRoot.active;
        this.unit_icon_prefab = AssetsMgr.prefabMap.get('Unit_Icon');
        this.itemPrefab_1 = AssetsMgr.prefabMap.get('FactoryBuildItem');
        this.itemPrefab_2 = AssetsMgr.prefabMap.get('TechnologyItem');
        this.itemPrefab_3 = AssetsMgr.prefabMap.get('RelicItem');

        GameEventMgr.Register(this, GameEvent.GameStart, this.RefreshViewUI.bind(this));
        GameEventMgr.Register(this, GameEvent.PlayerDataChange, this.RefreshViewUI.bind(this));
    }

    public OnClickShowViewTab(event: EventHandler, customEventData: string) {
        let pageType = Number(customEventData);
        this._isShowTab = this.currentPageType != pageType || !this._isShowTab;
        this.contentRoot.active = this._isShowTab;

        this.RefreshViewUI(this.target_factory, pageType);
        // let angle = this._isShowTab ? 0 : 180;
        // event.target.getChildByName("Icon").setRotationFromEuler(0, 0, angle);
    }

    public RefreshViewUI(target?: FactoryCom, pageType?: number) {

        let clear = false;
        if (!pageType || pageType != this.currentPageType) {
            this.content.destroyAllChildren();
            clear = true;
        }
        this.currentPageType = pageType || this.currentPageType;
        let factory = target || this.target_factory;

        this.txtTechnologyPoint.string = Global.gameManager.playerData.technologyPoint + '';
        if (!factory || !factory.spawner) return;

        let getCache = (index) => {
            let child = this.content.children[index];
            if (child && !clear) {
                return child;
            }
            if (this.currentPageType == 1) {
                let item = instantiate(this.itemPrefab_1).getComponent(FactoryBuildItem);
                item.node.parent = this.content;
                let icon = instantiate(this.unit_icon_prefab);
                icon.parent = item.icon_node;
                return item.node;
            }
            else if (this.currentPageType == 2) {

                let item = instantiate(this.itemPrefab_2);
                item.parent = this.content;
                item.active = true;
                return item;
            }
            else if (this.currentPageType == 3) {

                let item = instantiate(this.itemPrefab_3);
                item.parent = this.content;
                item.active = true;
                return item;
            }
        }

        let count = 0;
        if (this.currentPageType == 1) {//制造
            let all_units: Set<string> = new Set;
            for (let i = 0; i < Global.config['levelCfg'].length; i++) {
                let spawnerCfg = Global.config['levelCfg'][i].unit_unlocked;
                if (spawnerCfg && spawnerCfg.length > 0) {
                    spawnerCfg.forEach((v: string) => {
                        all_units.add(v);
                    })
                }
            }

            all_units.forEach((type: string) => {
                let item = getCache(count++).getComponent(FactoryBuildItem);
                let icon = item.icon_node.children[0];
                item.clickCallback = this.tryProduce.bind(this);
                item.node.active = true;
                item.economic = UICtrl.Instance.economicViewUI.target_economic;
                let workShop = factory.spawner.getWorkshop(UnitType[type]);
                if (workShop) {
                    item.workShop = workShop;
                }
                else {
                    item.product_count.string = '';
                    item.progress_mask.fillRange = 1;
                }
                let msg = UnitMsg.msgMap.get(UnitType[type]);
                AssetsMgr.getRes(msg.iconPath, SpriteFrame, (sp) => {
                    if (icon && icon.isValid) {
                        icon.getChildByName('Icon').getComponent(Sprite).spriteFrame = sp;
                        icon.getChildByName('Name').getComponent(Label).string = msg.name;
                    }
                });
            })
        }
        else if (this.currentPageType == 2) {//科技

            TechnologyData.TechnologyMap.forEach((v, k) => {
                let item = getCache(count++).getComponent(TechnologyItem);
                item.technologyType = k;
                item.node.active = true;
            })
        }
        else if (this.currentPageType == 3) {//遗物

            RelicData.RelicMap.forEach((v, k) => {
                let item = getCache(count++).getComponent(RelicItem);
                item.relicType = k;
                item.node.active = true;
            })
        }
        // this.content.getComponent(Layout).updateLayout();
    }

    private tryProduce(workShop: Workshop) {
        if (!workShop) {
            return;
        }
        let unit = workShop.prefeb.data.getComponent(Tools.getEnumName(UnitType, workShop.productType));
        let economic = UICtrl.Instance.economicViewUI.target_economic;
        let producingCost = workShop.spawner.GetElectricConsume_afterCompletingProduction();
        if (economic.HasUnitRes(unit, producingCost, true)) {
            economic.CostRes(unit.spawn_cost);
            workShop.AddProductNum(1);
            SoundCtrl.playEffect('forceField_000', 0.2);
        }
        else {
            SoundCtrl.playEffect('mouserelease1');
        }
    }

}


